﻿using System;
using System.Collections.Generic;
using System.Threading;
using RikaScript.Logger;

namespace RikaScript
{
    /// <summary>
    /// 异步解析引擎
    /// </summary>
    public class AsyncEngine
    {
        /// <summary>
        /// 引擎
        /// </summary>
        private readonly Engine _engine;

        /// <summary>
        /// 代码队列
        /// </summary>
        private readonly Queue<string> _codeList = new Queue<string>();

        /// <summary>
        /// 代码解析线程
        /// </summary>
        private readonly Thread _thread;

        /// <summary>
        /// 当没有代码时每次检查新代码的时间间隔
        /// </summary>
        private const int PauseWaitingTime = 10;

        public AsyncEngine(Engine engine)
        {
            _engine = engine;
            _thread = new Thread(Running);
            _thread.Start();
        }

        /// <summary>
        /// 执行代码
        /// </summary>
        public void Execute(string code)
        {
            foreach (var s in code.Split('\n'))
            {
                _codeList.Enqueue(s);
            }
        }

        /// <summary>
        /// 异步循环调用的代码执行方法
        /// </summary>
        private void Running()
        {
            while (true)
            {
                if (_codeList.Count > 0)
                {
                    var peek = _codeList.Dequeue();
                    if (peek.Trim().Length > 0)
                    {
                        _engine.Execute(peek);
                    }
                }
                else
                {
                    Thread.Sleep(PauseWaitingTime);
                }
            }
        }
    }
}